package org.chen.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.email.dto.EmailConfigDTO;
import org.chen.system.service.SystemConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Properties;

/**
 * 动态邮件配置服务
 * 支持数据库配置优先，application.yml作为备用配置
 */
@Service
@Slf4j
public class DynamicEmailConfigService {

    @Autowired
    private SystemConfigService systemConfigService;

    // 从application.yml读取默认配置
    @Value("${flight.smtp-host:smtp.qq.com}")
    private String defaultSmtpHost;

    @Value("${flight.smtp-port:587}")
    private Integer defaultSmtpPort;

    @Value("${flight.smtp-username:}")
    private String defaultSmtpUsername;

    @Value("${flight.smtp-password:}")
    private String defaultSmtpPassword;

    /**
     * 获取有效的邮件配置
     * 优先级：数据库配置 > application.yml配置
     */
    public EffectiveEmailConfig getEffectiveEmailConfig() {
        EmailConfigDTO dbConfig = systemConfigService.getEmailConfig();
        
        EffectiveEmailConfig effectiveConfig = new EffectiveEmailConfig();
        
        // 如果数据库中启用了邮件功能且配置完整，则使用数据库配置
        if (dbConfig.getEnabled() && isConfigComplete(dbConfig)) {
            log.info("使用数据库中的邮件配置");
            effectiveConfig.setEnabled(true);
            effectiveConfig.setSmtpHost(dbConfig.getSmtpHost());
            effectiveConfig.setSmtpPort(dbConfig.getSmtpPort());
            effectiveConfig.setUsername(dbConfig.getUsername());
            effectiveConfig.setPassword(dbConfig.getPassword());
            effectiveConfig.setFromEmail(dbConfig.getFromEmail());
            effectiveConfig.setSsl(dbConfig.getSsl());
            effectiveConfig.setSource("database");
        } 
        // 否则使用application.yml中的默认配置
        else if (isDefaultConfigComplete()) {
            log.info("使用application.yml中的默认邮件配置");
            effectiveConfig.setEnabled(true);
            effectiveConfig.setSmtpHost(defaultSmtpHost);
            effectiveConfig.setSmtpPort(defaultSmtpPort);
            effectiveConfig.setUsername(defaultSmtpUsername);
            effectiveConfig.setPassword(defaultSmtpPassword);
            effectiveConfig.setFromEmail(defaultSmtpUsername); // 默认发件人使用用户名
            effectiveConfig.setSsl(true); // 默认启用SSL
            effectiveConfig.setSource("application.yml");
        }
        // 都没有完整配置，则禁用邮件功能
        else {
            log.warn("邮件配置不完整，禁用邮件功能");
            effectiveConfig.setEnabled(false);
            effectiveConfig.setSource("none");
        }
        
        return effectiveConfig;
    }

    /**
     * 创建动态JavaMailSender
     */
    public JavaMailSender createDynamicMailSender() {
        EffectiveEmailConfig config = getEffectiveEmailConfig();
        
        if (!config.getEnabled()) {
            throw new RuntimeException("邮件配置未启用或配置不完整");
        }

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(config.getSmtpHost());
        mailSender.setPort(config.getSmtpPort());
        mailSender.setUsername(config.getUsername());
        mailSender.setPassword(config.getPassword());

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", config.getSsl());
        props.put("mail.debug", "false");

        log.info("创建动态邮件发送器成功，配置来源：{}", config.getSource());
        return mailSender;
    }

    /**
     * 测试邮件配置
     */
    public boolean testEmailConfig(String testEmail) {
        try {
            EffectiveEmailConfig config = getEffectiveEmailConfig();
            if (!config.getEnabled()) {
                return false;
            }

            JavaMailSender mailSender = createDynamicMailSender();
            
            // 发送测试邮件的逻辑
            log.info("邮件配置测试成功，配置来源：{}", config.getSource());
            return true;
        } catch (Exception e) {
            log.error("邮件配置测试失败", e);
            return false;
        }
    }

    /**
     * 检查数据库配置是否完整
     */
    private boolean isConfigComplete(EmailConfigDTO config) {
        return StringUtils.hasText(config.getSmtpHost()) &&
               config.getSmtpPort() != null &&
               StringUtils.hasText(config.getUsername()) &&
               StringUtils.hasText(config.getPassword()) &&
               StringUtils.hasText(config.getFromEmail());
    }

    /**
     * 检查默认配置是否完整
     */
    private boolean isDefaultConfigComplete() {
        return StringUtils.hasText(defaultSmtpHost) &&
               defaultSmtpPort != null &&
               StringUtils.hasText(defaultSmtpUsername) &&
               StringUtils.hasText(defaultSmtpPassword);
    }

    /**
     * 有效邮件配置类
     */
    public static class EffectiveEmailConfig {
        private Boolean enabled;
        private String smtpHost;
        private Integer smtpPort;
        private String username;
        private String password;
        private String fromEmail;
        private Boolean ssl;
        private String source; // 配置来源：database, application.yml, none

        // Getters and Setters
        public Boolean getEnabled() { return enabled; }
        public void setEnabled(Boolean enabled) { this.enabled = enabled; }

        public String getSmtpHost() { return smtpHost; }
        public void setSmtpHost(String smtpHost) { this.smtpHost = smtpHost; }

        public Integer getSmtpPort() { return smtpPort; }
        public void setSmtpPort(Integer smtpPort) { this.smtpPort = smtpPort; }

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }

        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }

        public String getFromEmail() { return fromEmail; }
        public void setFromEmail(String fromEmail) { this.fromEmail = fromEmail; }

        public Boolean getSsl() { return ssl; }
        public void setSsl(Boolean ssl) { this.ssl = ssl; }

        public String getSource() { return source; }
        public void setSource(String source) { this.source = source; }
    }
}
